package a07_二叉树;

/**
 * <p>
 * a26_二叉搜索树的最近公共祖先复习1
 * </p>
 *
 * @author flyduck
 * @since 2024/12/25
 */
public class a26_二叉树的最近公共祖先复习1 {
    //
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if(root == p || root == q){//假设root=p，q在p之下，那么直接返回p也是可以的 leftNode != null && rightNode == null
            return root;
        }

        TreeNode leftNode = lowestCommonAncestor(root.left, p, q);
        TreeNode rightNode = lowestCommonAncestor(root.right, p, q);

        if (leftNode != null && rightNode != null) {
            return root;
        }else if(leftNode != null && rightNode == null){
            return leftNode;
        }else if(leftNode == null && rightNode != null){
            return rightNode;
        }else {
            return null;
        }
    }
}
